/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/record', 'N/search'], function (record, search) {
    var newRecord, startoperationValue, woUnits, results;

    function beforeSubmit(context) {
        //删除 相关总账影响记录
        if (context.type === 'delete') {
            var woId = context.oldRecord.getValue('createdfrom');
            var operationNumber = context.newRecord.getText('startoperation');
            var identify = context.oldRecord.getText('custbody_identify');
            var operationCharCode = String.fromCharCode(64 + parseInt(operationNumber));
            var identifyCharCode = String.fromCharCode(64 + parseInt(identify));
            var comCode = 'Y' + operationCharCode + identifyCharCode;
            var fieldLookUp1 = search.lookupFields({
                type: 'workorder',
                id: woId,
                columns: ['custbody_gl_impact_record']
            });
            var oldGLImpact = fieldLookUp1.custbody_gl_impact_record;
            var strArray = oldGLImpact.split('|');
            for (var index in strArray) {
                if (strArray[index].indexOf(comCode) !== -1) {
                    strArray[index] = 'D';
                }
            }
            var newGLImpact = strArray.join('|');
            record.submitFields({type: 'workorder', id: woId, values: {custbody_gl_impact_record: newGLImpact}});
        }

        //删除  相关工单工序详情    已完成数量 报工数量 次品数量 工序废品数量 成品废品数量
        //删除  相关工单工序详情货品  耗料数量  发料数量
        if (context.type === 'delete') {
            var operationNumber = context.newRecord.getText('startoperation');
            var woId = context.oldRecord.getValue('createdfrom');
            var wo = record.load({type: 'workorder', id: woId, isDynamic: true});
            var assemblyItemId = wo.getValue('assemblyitem');
            var detailId;
            search.create({
                type: 'customrecord_workorder_process_detail',
                columns: [],
                filters: [['custrecord_workordernum', 'is', woId],
                    'and', ['custrecord_processnum', 'equalto', Number(operationNumber)],
                    'and', ['custrecord_assembly', 'is', assemblyItemId]]
            }).run().each(function (result) {
                detailId = result.id;
            });
            if (detailId) {//已完成数量 报工数量 次品数量 工序废品数量 成品废品数量
                var detailRec = record.load({
                    type: 'customrecord_workorder_process_detail',
                    id: detailId,
                    isDynamic: true
                });
                var completeQty = detailRec.getValue('custrecord_completedquantity');
                var reportQty = detailRec.getValue('custrecord_reportworkquantity');
                var defectiveQty = detailRec.getValue('custrecord_defectiveqty');
                var scrapQty = detailRec.getValue('custrecord_scrapquantity');
                var finishedscrapQty = detailRec.getValue('custrecord_finishedscrapqty');

                var currcompleteQty = context.newRecord.getValue('completedquantity');
                var currreportQty = context.newRecord.getValue('custbody_reportwork_qty');
                var currdefectiveQty = context.newRecord.getValue('custrecord_defectiveqty');
                var currscrapQty = context.newRecord.getValue('custrecord_finishedscrapqty');
                var currfinishedscrapQty = context.newRecord.getValue('custrecord_finishedscrapqty');

                detailRec.setValue('custrecord_completedquantity', completeQty - currcompleteQty);
                detailRec.setValue('custrecord_reportworkquantity', reportQty - currreportQty);
                detailRec.setValue('custrecord_defectiveqty', defectiveQty - currdefectiveQty);
                detailRec.setValue('custrecord_scrapquantity', scrapQty - currscrapQty);
                detailRec.setValue('custrecord_finishedscrapqty', finishedscrapQty - currfinishedscrapQty);

                if (context.newRecord.getValue('isbackflush')) {//工单完成及反冲
                    for (var i = 0; i < context.newRecord.getLineCount('component'); i++) {
                        if (operationNumber == context.newRecord.getSublistText('component', 'operationsequencenumber', i)) {
                            var itemId = context.newRecord.getSublistValue('component', 'item', i);
                            if (itemId !== '868' && itemId !== '49' && itemId !== '866') {
                                var line = detailRec.findSublistLineWithValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);
                                if (line !== -1) {
                                    var issueQuantity = context.newRecord.getSublistValue('component', 'quantity', i);
                                    var originIssueQty = detailRec.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', line);
                                    //删除工单工序详情  货品行的耗料数量
                                    detailRec.selectLine('recmachcustrecord_workorderprocess', line);
                                    detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', originIssueQty - issueQuantity);//设置耗料数量
                                    detailRec.commitLine('recmachcustrecord_workorderprocess');
                                }
                            }
                        }
                    }
                }


                detailRec.save();
            }
            // 删除库存转移单、库存调整单
            // 采购单收货取消核销勾选
        }

        //更新  相关工单工序详情 已完成数量 报工数量 次品数量 工序废品数量 成品废品数量
        if (context.type === 'edit') {
            var operationNumber = context.newRecord.getText('startoperation');
            var woId = context.newRecord.getValue('createdfrom');
            var wo = record.load({type: 'workorder', id: woId, isDynamic: true});
            var assemblyItemId = wo.getValue('assemblyitem');
            var detailId;
            search.create({
                type: 'customrecord_workorder_process_detail',
                columns: [],
                filters: [['custrecord_workordernum', 'is', woId],
                    'and', ['custrecord_processnum', 'equalto', Number(operationNumber)],
                    'and', ['custrecord_assembly', 'is', assemblyItemId]]
            }).run().each(function (result) {
                detailId = result.id;
            });
            if (detailId) {//已完成数量 报工数量 次品数量 工序废品数量 成品废品数量
                var detailRec = record.load({
                    type: 'customrecord_workorder_process_detail',
                    id: detailId,
                    isDynamic: true
                });
                var completeQty = detailRec.getValue('custrecord_completedquantity');
                var reportQty = detailRec.getValue('custrecord_reportworkquantity');
                var defectiveQty = detailRec.getValue('custrecord_defectiveqty');
                var scrapQty = detailRec.getValue('custrecord_scrapquantity');
                var finishedscrapQty = detailRec.getValue('custrecord_finishedscrapqty');

                var oldcompleteQty = context.oldRecord.getValue('completedquantity');
                var oldreportQty = context.oldRecord.getValue('custbody_reportwork_qty');
                var olddefectiveQty = context.oldRecord.getValue('custrecord_defectiveqty');
                var oldscrapQty = context.oldRecord.getValue('custrecord_finishedscrapqty');
                var oldfinishedscrapQty = context.oldRecord.getValue('custrecord_finishedscrapqty');

                var currcompleteQty = context.newRecord.getValue('completedquantity');
                var currreportQty = context.newRecord.getValue('custbody_reportwork_qty');
                var currdefectiveQty = context.newRecord.getValue('custrecord_defectiveqty');
                var currscrapQty = context.newRecord.getValue('custrecord_finishedscrapqty');
                var currfinishedscrapQty = context.newRecord.getValue('custrecord_finishedscrapqty');

                detailRec.setValue('custrecord_completedquantity', completeQty + (currcompleteQty - oldcompleteQty));
                detailRec.setValue('custrecord_reportworkquantity', oldreportQty + (currreportQty - oldreportQty));
                detailRec.setValue('custrecord_defectiveqty', defectiveQty + (currdefectiveQty - olddefectiveQty));
                detailRec.setValue('custrecord_scrapquantity', scrapQty + (currscrapQty - oldscrapQty));
                detailRec.setValue('custrecord_finishedscrapqty', finishedscrapQty + (currfinishedscrapQty - oldfinishedscrapQty));


                if (context.newRecord.getValue('isbackflush')) {//工单完成及反冲
                    for (var i = 0; i < context.newRecord.getLineCount('component'); i++) {
                        if (operationNumber == context.newRecord.getSublistText('component', 'operationsequencenumber', i)) {
                            var itemId = context.newRecord.getSublistValue('component', 'item', i);
                            if (itemId !== '868' && itemId !== '49' && itemId !== '866') {
                                var line = detailRec.findSublistLineWithValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);
                                if (line !== -1) {
                                    var currIssueQuantity = context.newRecord.getSublistValue('component', 'quantity', i);
                                    var oldIssueQuantity = context.oldRecord.getSublistValue('component', 'quantity', i);
                                    var originIssueQty = detailRec.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', line);
                                    //更新工单工序详情  货品行的耗料数量
                                    detailRec.selectLine('recmachcustrecord_workorderprocess', line);
                                    detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', originIssueQty + (currIssueQuantity - oldIssueQuantity));//设置耗料数量
                                    detailRec.commitLine('recmachcustrecord_workorderprocess');
                                }
                            }
                        }
                    }
                }

                detailRec.save();
            }

            //修改相关库存转移单、库存调整单
            

        }

        if (context.type === 'create') {
            try {
                newRecord = context.newRecord;
                var woId = context.newRecord.getValue('createdfrom');
                var wo = record.load({type: 'workorder', id: woId, isDynamic: true});
                var operationtaskSearch = search.create({
                    type: 'manufacturingoperationtask',
                    columns: [],
                    filters: [['workorder', 'is', woId]]
                });
                results = operationtaskSearch.run().getRange(0, 100);
                var lastprocessnum = results.length;//最后一道工序号
                var assemblyitemId = wo.getValue('assemblyitem');//工单装配件id
                var startoperationText = context.newRecord.getText('startoperation');
                startoperationValue = context.newRecord.getValue('startoperation');
                woUnits = context.newRecord.getValue('units');
                var woLocationId = wo.getValue('location');
                var woSubsidiaryId = wo.getValue('subsidiary');
                var assemblyItem = record.load({type: search.Type.ASSEMBLY_ITEM, id: assemblyitemId, isDynamic: true});

                //产生库存调整单
                //下面注释的文档好像没出现了
                /*//无论反冲非反冲  最后一道工序 单条,库存调整单  //装配件  //装配件sku
                if (lastprocessnum == startoperationText) {//判断是最后一道工序
                    var stockunit = assemblyItem.getText('stockunit');//库存单位
                    var baseunit = assemblyItem.getText('baseunit');//基本单位
                    var unitstypeId = assemblyItem.getValue('unitstype');//单位类型
                    var singlesku = assemblyItem.getText('custitem_single_sku');
                    var conversionrate;
                    search.create({
                        type: 'unitstype', columns: ['conversionrate'],
                        filters: [['unitname', 'is', stockunit], 'and', ['internalid', 'is', unitstypeId]]
                    }).run().each(function (result) {
                        conversionrate = Number(result.getValue('conversionrate'));
                    });//获得库存单位  对 基本单位 的转化率
                    if (conversionrate !== 1) {
                        var lastprocessCompletedquantity = Number(context.newRecord.getValue('completedquantity'));
                        log.debug('lastprocessCompletedquantity', lastprocessCompletedquantity);
                        var mod = lastprocessCompletedquantity % conversionrate;
                        if (mod !== 0) {
                            var adjustquantity = mod;//调整数量
                            var invAdjst = record.create({type: record.Type.INVENTORY_ADJUSTMENT, isDynamic: true}); //1.调整装配件

                            invAdjst.setValue('subsidiary', woSubsidiaryId); //子公司
                            invAdjst.setValue('account', 53); //调整科目3200 Opening Balance
                            invAdjst.setValue('custbody_relatedtransation', context.newRecord.id); //相关单据

                            invAdjst.selectNewLine('inventory'); //库存调整单  行
                            invAdjst.setCurrentSublistValue('inventory', 'item', assemblyitemId); //货品（行） 装配件SKU及名称
                            //invAdjst.setCurrentSublistText('inventory', 'units', baseunit);//单位（行）
                            invAdjst.setCurrentSublistValue('inventory', 'location', woLocationId); //地点（行)  work order 的location
                            invAdjst.setCurrentSublistValue('inventory', 'adjustqtyby', -adjustquantity);//调整数量（行）
                            //invAdjst.setCurrentSublistValue('inventory', 'unitcost', 0); //估计单位成本（行）  自动带出
                            try {
                                var inventoryDetailRec = invAdjst.getCurrentSublistSubrecord('inventory', 'inventorydetail');
                                inventoryDetailRec.selectNewLine('inventoryassignment');
                                inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'binnumber', 3);//线边仓-生产区
                                inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'quantity', -adjustquantity);
                                inventoryDetailRec.commitLine('inventoryassignment');
                            } catch (e) {
                                log.debug('set  inventoryassignment  detail error', JSON.stringify(e));
                            }
                            invAdjst.commitLine('inventory');

                            invAdjst.selectNewLine('inventory'); //库存调整单  行
                            invAdjst.setCurrentSublistText('inventory', 'item', singlesku); //货品（行） singlesku
                            //invAdjst.setCurrentSublistValue('inventory', 'units', baseunit);//单位（行）
                            invAdjst.setCurrentSublistValue('inventory', 'location', 1); //地点（行)  线边仓
                            invAdjst.setCurrentSublistValue('inventory', 'adjustqtyby', adjustquantity);//调整数量（行）
                            //invAdjst.setCurrentSublistValue('inventory', 'unitcost', 0); //估计单位成本（行）自动带出
                            try {
                                var inventoryDetailRec = invAdjst.getCurrentSublistSubrecord('inventory', 'inventorydetail');
                                inventoryDetailRec.selectNewLine('inventoryassignment');
                                inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'binnumber', 3);//线边仓-生产区
                                inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'quantity', adjustquantity);
                                inventoryDetailRec.commitLine('inventoryassignment');
                            } catch (e) {
                                log.debug('283 set  inventoryassignment  detail error', JSON.stringify(e));
                            }
                            invAdjst.commitLine('inventory');
                            var invAdjstId;
                            try {
                                invAdjstId = invAdjst.save();
                            } catch (e) {
                                log.debug('创建库存调整单失败', JSON.stringify(e));
                                throw "291创建库存调整单失败：" + e.message;
                            }
                            log.debug('最后一道工序库存调整单', invAdjstId)
                        }
                    }
                }
                log.debug('工序号', startoperationText);*/


                //无论反冲非反冲 无论哪道工序有 有次品数量、废品数量,创建库存调整单   //装配件  //item
                var defectivequantity = context.newRecord.getValue('custbody_defectivequantity');
                var processscrapquantity = context.newRecord.getValue('custbody_processscrapquantity');
                //废品数量
                if (Number(defectivequantity) > 0 || Number(processscrapquantity) > 0) {
                    log.debug("有次废品");
                    var invAdjst = record.create({type: record.Type.INVENTORY_ADJUSTMENT, isDynamic: true});
                    invAdjst.setValue('subsidiary', woSubsidiaryId); //子公司
                    invAdjst.setValue('account', 53); //调整科目3200 Opening Balance
                    invAdjst.setValue('custbody_relatedtransation', context.newRecord.id); //相关单据
                    //当出现多少废品，这个库存调整单的绍兴沐家废品仓就增加多少个装配件的数量
                    if (Number(processscrapquantity) > 0) {
                        invAdjst.selectNewLine('inventory'); //库存调整单  行
                        invAdjst.setCurrentSublistValue('inventory', 'item', assemblyitemId); //货品（行） 装配件SKU及名称
                        //invAdjst.setCurrentSublistText('inventory', 'units', baseunit);//单位（行）
                        invAdjst.setCurrentSublistValue('inventory', 'location', 47); //地点（行)  废品仓
                        invAdjst.setCurrentSublistValue('inventory', 'adjustqtyby', Number(processscrapquantity));//调整数量（行）  废品数量
                        //invAdjst.setCurrentSublistValue('inventory', 'unitcost', 0); //估计单位成本（行）  自动带出
                        try {
                            var inventoryDetailRec = invAdjst.getCurrentSublistSubrecord('inventory', 'inventorydetail');
                            inventoryDetailRec.selectNewLine('inventoryassignment');
                            //inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'binnumber', '');//绍兴沐家废品仓   暂不填写库位
                            inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'quantity', Number(processscrapquantity));
                            inventoryDetailRec.commitLine('inventoryassignment');
                        } catch (e) {
                            //有些item不需要填写库存详情，没有库位的货品
                        }
                        invAdjst.commitLine('inventory');

                        var invAdjstId;
                        try {
                            invAdjstId = invAdjst.save();
                            log.debug("invAdjstId", invAdjstId);
                        } catch (e) {
                            log.debug('创建库存调整单失败', JSON.stringify(e));
                            throw " 创建库存调整单失败：" + e.message;
                        }
                    }
                    //当出现多少次品，在库存调整单上装配件的线边仓的二次利用区就要增加多少个，
                    if (Number(defectivequantity) > 0) {
                        invAdjst.selectNewLine('inventory'); //库存调整单  行
                        invAdjst.setCurrentSublistValue('inventory', 'item', assemblyitemId); //货品（行） 装配件SKU及名称
                        //invAdjst.setCurrentSublistText('inventory', 'units', baseunit);//单位（行）
                        invAdjst.setCurrentSublistValue('inventory', 'location', woLocationId); //地点（行)  work order 的location
                        invAdjst.setCurrentSublistValue('inventory', 'adjustqtyby', Number(defectivequantity));//调整数量（行）  次品数量
                        //invAdjst.setCurrentSublistValue('inventory', 'unitcost', 0); //估计单位成本（行）  自动带出
                        try {
                            var inventoryDetailRec = invAdjst.getCurrentSublistSubrecord('inventory', 'inventorydetail');
                            inventoryDetailRec.selectNewLine('inventoryassignment');
                            //inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'binnumber', '');//绍兴沐家废品仓   暂不填写库位
                            inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'quantity', Number(defectivequantity));//次品数量
                            inventoryDetailRec.commitLine('inventoryassignment');
                        } catch (e) {
                            //有些item不需要填写库存详情，报错不需要处理
                        }
                        invAdjst.commitLine('inventory');
                        //同时这道工序对应所有非费用货品的单个BOM对应数量x次品数在库存调整单的线边仓生产区减少这个数量
                        for (var i = 0; i < context.newRecord.getLineCount('component'); i++) {
                            if (startoperationText == context.newRecord.getSublistText('component', 'operationsequencenumber', i)) {
                                var itemId = context.newRecord.getSublistValue('component', 'item', i);
                                if (itemId !== '868' && itemId !== '49' && itemId !== '866') {
                                    var quantityper = context.newRecord.getSublistValue('component', 'quantityper', i);
                                    var adjstquantity = quantityper * defectivequantity;
                                    invAdjst.selectNewLine('inventory'); //库存调整单  行
                                    invAdjst.setCurrentSublistValue('inventory', 'item', itemId); //货品（行）
                                    //invAdjst.setCurrentSublistValue('inventory', 'units', baseunit);//单位（行）
                                    invAdjst.setCurrentSublistValue('inventory', 'location', woLocationId); //地点（行)  线边仓-二次利用区(不能填) 暂时放到废品区
                                    invAdjst.setCurrentSublistValue('inventory', 'adjustqtyby', -adjstquantity);//调整数量（行）
                                    //invAdjst.setCurrentSublistValue('inventory', 'unitcost', 0); //估计单位成本（行）自动带出
                                    try {
                                        var inventoryDetailRec = invAdjst.getCurrentSublistSubrecord('inventory', 'inventorydetail');
                                        inventoryDetailRec.selectNewLine('inventoryassignment');
                                        inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'binnumber', 3);//线边仓-生产区
                                        inventoryDetailRec.setCurrentSublistValue('inventoryassignment', 'quantity', -adjstquantity);
                                        inventoryDetailRec.commitLine('inventoryassignment');
                                    } catch (e) {
                                        //有些item不需要填写库存详情，报错不需要处理
                                    }
                                    invAdjst.commitLine('inventory');
                                }
                            }
                        }
                        var invAdjstId;
                        try {
                            invAdjstId = invAdjst.save();
                            log.debug("invAdjstId", invAdjstId);
                        } catch (e) {
                            log.debug('创建库存调整单失败', JSON.stringify(e));
                            throw " 创建库存调整单失败：" + e.message;
                        }
                    }
                }

                //产生库存调整单


                //插入工单工序详情
                var isbackflush = context.newRecord.getValue('isbackflush');
                if (isbackflush) {//反冲
                    // checkPoItemReceiptBackFlush(context, woId);//勾选采购单 倒冲加工费
                    if (context.type === 'create') {
                        //插入“工单工序详情”列表 及 明细行
                        createOrUpdateProcessDetailRecordAndItems(woId, startoperationText, assemblyitemId);
                        //插入 下一道“工单工序详情”列表  及 明细行
                        if (lastprocessnum != startoperationText) {
                            createOrUpdateNextProcessDetailRecordAndItems(woId, startoperationText, assemblyitemId);
                        }
                    }
                } else if (!isbackflush) {//非反冲
                    if (context.type === 'create') {
                        //插入“工单工序详情”列表 及 明细行
                        createOrUpdateProcessDetailRecordAndItemsCompletion(woId, startoperationText, assemblyitemId);
                        //插入 下一道“工单工序详情”列表  及 明细行
                        if (lastprocessnum != startoperationText) {
                            createOrUpdateNextProcessDetailRecordAndItemsCompletion(woId, startoperationText, assemblyitemId);
                        }
                    }
                }
                checkPoItemReceiptBackFlush(context, woId);

            } catch (e) {
                log.debug('e', JSON.stringify(e));
                record.delete({
                    type: 'inventorytransfer',
                    id: context.newRecord.getValue('custbody_related_itid')
                });
                // record.delete({
                //     type:record.type.WORK_ORDER_COMPLETION,
                //     id:context.newRecord.id
                // });

                throw e;
            }
        }

    }

    function afterSubmit(context) {
        log.debug('context.type', context.type);

        if (context.type === 'delete' || context.type === 'edit') {
            return;
        }


    }

    function checkPoItemReceiptBackFlush(context, woId) {
        for (var i = 0; i < context.newRecord.getLineCount('component'); i++) {
            var itemId = context.newRecord.getSublistValue('component', 'item', i);
            if (itemId === '868' || itemId === '49' || itemId === '866') {
                var startoperationText = context.newRecord.getText('startoperation');
                var operationsequencenumber = context.newRecord.getSublistValue('component', 'operationsequencenumber', i);
                if (operationsequencenumber === startoperationText) {
                    var poId;
                    search.create({  //查找该工序的费用货品对应的采购订单Id
                        type: 'purchaseorder',
                        columns: [],
                        filters: [['createdfrom', 'is', woId], 'and', ['anylineitem', 'is', itemId]]
                    }).run().each(function (result) {
                        poId = result.id;
                    });
                    if (poId) {  //如果有采购订单  则查找采购订单对应的  未勾选“倒冲加工费” 收货单
                        search.create({
                            type: 'itemreceipt',
                            columns: [],
                            filters: [['createdfrom', 'is', poId],
                                'and', ['mainline', 'is', 'T'],
                                'and', ['custbody_backflushprocessingfee', 'is', 'F']]
                        }).run().each(function (result) {
                            var itemReceiptId = result.id;
                            if (itemReceiptId) {
                                record.submitFields({
                                    type: 'itemreceipt',
                                    id: itemReceiptId,
                                    values: {'custbody_backflushprocessingfee': true}
                                });
                            }
                            return true;
                        });
                    }
                }
            }
        }
    }

    function getProcessTypeIdByOperationTaskId(operationTaskId) {
        var fieldLookUp1 = search.lookupFields({
            type: 'manufacturingoperationtask',
            id: operationTaskId,
            columns: ['manufacturingcosttemplate']
        });
        var manufacturingcosttemplateId = fieldLookUp1.manufacturingcosttemplate[0].value;
        var fieldLookUp2 = search.lookupFields({
            type: 'manufacturingcosttemplate',
            id: manufacturingcosttemplateId,
            columns: ['custrecord_processtype']
        });
        return fieldLookUp2.custrecord_processtype[0].value;
    }

    function createOrUpdateProcessDetailRecordAndItems(woId, startoperationText, assemblyItemId) {
        var detailId;
        search.create({
            type: 'customrecord_workorder_process_detail',
            columns: [],
            filters: [['custrecord_workordernum', 'is', woId],
                'and', ['custrecord_processnum', 'equalto', Number(startoperationText)],
                'and', ['custrecord_assembly', 'is', assemblyItemId]]
        }).run().each(function (result) {
            detailId = result.id;
        });
        if (!detailId) { //不存在
            //创建工单工序详情
            var detailRec = record.create({type: 'customrecord_workorder_process_detail', isDynamic: true});
            detailRec.setValue('custrecord_workordernum', woId); // 工单号
            detailRec.setValue('custrecord_processnum', Number(startoperationText));//工序号
            detailRec.setValue('custrecord_assembly', assemblyItemId);//装配品
            detailRec.setValue('custrecord_externalprocess', startoperationValue);// 工序
            detailRec.setValue('custrecord_process_type', getProcessTypeIdByOperationTaskId(startoperationValue));//工序类型
            detailRec.setValue('custrecord_workunit', woUnits);//单位
            detailRec.setValue('custrecord_reportworkquantity', newRecord.getValue('custbody_reportwork_qty'));//报工数量
            detailRec.setValue('custrecord_completedquantity', newRecord.getValue('completedquantity'));//已完成数量
            detailRec.setValue('custrecord_defectiveqty', newRecord.getValue('custbody_defectivequantity') === "" ? 0 : newRecord.getValue('custbody_defectivequantity'));//次品数量
            detailRec.setValue('custrecord_scrapquantity', newRecord.getValue('custbody_processscrapquantity') === "" ? 0 : newRecord.getValue('custbody_processscrapquantity'));//工序废品数量
            //创建工单工序详情明细行
            for (var i = 0; i < newRecord.getLineCount('component'); i++) {
                var processNum = newRecord.getText('startoperation');//工序号
                var operationsequencenumber = newRecord.getSublistValue('component', 'operationsequencenumber', i);//货品行工序号
                if (Number(processNum) === Number(operationsequencenumber)) {
                    var itemId = newRecord.getSublistValue('component', 'item', i);//货品
                    if (itemId !== '868' && itemId !== '49' && itemId !== '866') {//非委外加工费货品
                        var issueQuantity = newRecord.getSublistValue('component', 'quantity', i);
                        var itemUnits = newRecord.getSublistValue('component', 'units', i);
                        //创建工单工序详情明细行
                        detailRec.selectNewLine('recmachcustrecord_workorderprocess');
                        detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);//设置货品
                        detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', issueQuantity);//设置耗料数量
                        detailRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_unit', itemUnits);//设置单位
                        detailRec.commitLine('recmachcustrecord_workorderprocess');
                    }
                }
            }

            detailRec.save();
        } else if (detailId) {//存在工单工序详情则,  更新报工,次品,废品,完工数量      更新货品明细行的耗料数量
            var detail = record.load({type: 'customrecord_workorder_process_detail', id: detailId, isDynamic: true});
            var oldcompletedquantity = detail.getValue('custrecord_completedquantity');
            var olddefectivequantity = detail.getValue('custrecord_defectiveqty');
            var oldscrapquantity = detail.getValue('custrecord_scrapquantity');
            var oldreportquantity = detail.getValue('custrecord_reportworkquantity');

            detail.setValue('custrecord_completedquantity', newRecord.getValue('completedquantity') + oldcompletedquantity);
            detail.setValue('custrecord_defectiveqty', newRecord.getValue('custbody_defectivequantity') + olddefectivequantity);
            detail.setValue('custrecord_scrapquantity', newRecord.getValue('custbody_processscrapquantity') + oldscrapquantity);
            detail.setValue('custrecord_reportworkquantity', newRecord.getValue('custbody_reportwork_qty') + oldreportquantity);

            //存在更新  货品明细行
            for (var i = 0; i < newRecord.getLineCount('component'); i++) {
                var a = newRecord.getText('startoperation');//工序号
                var b = newRecord.getSublistValue('component', 'operationsequencenumber', i);//货品行工序号
                if (Number(a) === Number(b)) {
                    var itemId = newRecord.getSublistValue('component', 'item', i);//货品
                    if (itemId !== '868' && itemId !== '49' && itemId !== '866') {//非委外加工费货品
                        var itemUnits = newRecord.getSublistValue('component', 'units', i);
                        var newIssueQty = newRecord.getSublistValue('component', 'quantity', i);
                        // var oldIssueQty = oldRecord.getSublistValue('component', 'quantity', i);

                        var lineNumber = detail.findSublistLineWithValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);
                        if (lineNumber !== -1) {//找到了需要更新的 工单工序明细行
                            var issueQty = detail.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', lineNumber);
                            detail.selectLine('recmachcustrecord_workorderprocess', lineNumber);
                            detail.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', issueQty + newIssueQty);
                            detail.commitLine('recmachcustrecord_workorderprocess');
                        } else {//没找到则 新建一行
                            //创建工单工序详情明细行
                            detail.selectNewLine('recmachcustrecord_workorderprocess');
                            detail.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_item', itemId);//设置货品
                            detail.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', newIssueQty);//设置耗料数量
                            detail.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_unit', itemUnits);//设置单位
                            detail.commitLine('recmachcustrecord_workorderprocess');
                        }
                    }
                }
            }
            detail.save();
        }
    }

    function createOrUpdateNextProcessDetailRecordAndItems(woId, startoperationText, assemblyItemId) {
        var detailNextId;
        var nextProcessNum = Number(startoperationText) + 1;
        search.create({
            type: 'customrecord_workorder_process_detail',
            columns: [],
            filters: [['custrecord_workordernum', 'is', woId],
                'and', ['custrecord_processnum', 'equalto', nextProcessNum],
                'and', ['custrecord_assembly', 'is', assemblyItemId]]
        }).run().each(function (result) {
            detailNextId = result.id;
        });

        if (!detailNextId) {//不存在下一道工单工序详情,则创建
            //创建下一道工单工序详情
            var detailNextRec = record.create({type: 'customrecord_workorder_process_detail', isDynamic: true});
            var operationTaskNextId = results[parseInt(startoperationText)].id;
            detailNextRec.setValue('custrecord_workordernum', woId);//工单号
            detailNextRec.setValue('custrecord_processnum', parseInt(startoperationText) + 1);//工序号
            detailNextRec.setValue('custrecord_assembly', assemblyItemId);//装配件
            detailNextRec.setValue('custrecord_externalprocess', operationTaskNextId);//单位
            detailNextRec.setValue('custrecord_process_type', getProcessTypeIdByOperationTaskId(operationTaskNextId));//工序类型
            detailNextRec.setValue('custrecord_workunit', woUnits);//工单单位

            //创建下一道工单工序详情明细行
            detailNextRec.selectNewLine('recmachcustrecord_workorderprocess');
            detailNextRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_item', assemblyItemId);//设置货品
            detailNextRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', newRecord.getValue('completedquantity'));//设置耗料数量
            detailNextRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_releasequantity', newRecord.getValue('completedquantity'));//设置发料数量
            detailNextRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_unit', woUnits);//设置单位
            detailNextRec.commitLine('recmachcustrecord_workorderprocess');

            detailNextRec.save();
        } else if (detailNextId) {//存在下一道工单工序详情
            var detailNext = record.load({
                type: 'customrecord_workorder_process_detail',
                id: detailNextId,
                isDynamic: true
            });
            var lineNumber = detailNext.findSublistLineWithValue('recmachcustrecord_workorderprocess', 'custrecord_item', assemblyItemId);
            if (lineNumber !== -1) {//找到了需要更新的 工单工序明细行
                var issueQty = detailNext.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', lineNumber);
                var releaseQty = detailNext.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_releasequantity', lineNumber);
                detailNext.selectLine('recmachcustrecord_workorderprocess', lineNumber);
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', issueQty + newRecord.getValue('completedquantity'));
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_releasequantity', releaseQty + newRecord.getValue('completedquantity'));//设置发料数量
                detailNext.commitLine('recmachcustrecord_workorderprocess');
            } else {//没找到则 新建一行
                //创建工单工序详情明细行
                detailNext.selectNewLine('recmachcustrecord_workorderprocess');
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_item', assemblyItemId);//设置货品
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', newRecord.getValue('completedquantity'));//设置耗料数量
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_releasequantity', newRecord.getValue('completedquantity'));//设置发料数量
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_unit', woUnits);//设置单位
                detailNext.commitLine('recmachcustrecord_workorderprocess');
            }
            detailNext.save();
        }
    }

    function createOrUpdateProcessDetailRecordAndItemsCompletion(woId, startoperationText, assemblyItemId) {
        var detailId;
        search.create({
            type: 'customrecord_workorder_process_detail',
            columns: ['internalid'],
            filters: [['custrecord_workordernum', 'is', woId],
                'and', ['custrecord_processnum', 'equalto', Number(startoperationText)],
                'and', ['custrecord_assembly', 'is', assemblyItemId]]
        }).run().each(function (result) {
            detailId = result.getValue('internalid');
        });
        if (!detailId) {//不存在本道工单工序详情,则创建
            //创建工单工序详情
            var detailRec = record.create({type: 'customrecord_workorder_process_detail', isDynamic: true});
            detailRec.setValue('custrecord_workordernum', woId); // 工单号
            detailRec.setValue('custrecord_processnum', Number(startoperationText));//工序号
            detailRec.setValue('custrecord_assembly', assemblyItemId);//装配品
            detailRec.setValue('custrecord_externalprocess', startoperationValue);// 工序
            detailRec.setValue('custrecord_process_type', getProcessTypeIdByOperationTaskId(startoperationValue));//工序类型
            detailRec.setValue('custrecord_workunit', woUnits);//单位
            detailRec.setValue('custrecord_reportworkquantity', newRecord.getValue('custbody_reportwork_qty'));//报工数量
            detailRec.setValue('custrecord_completedquantity', newRecord.getValue('completedquantity'));//已完成数量
            detailRec.setValue('custrecord_defectiveqty', newRecord.getValue('custbody_defectivequantity'));//次品数量
            detailRec.setValue('custrecord_scrapquantity', newRecord.getValue('custbody_processscrapquantity'));//工序废品数量
            detailRec.save();
        } else if (detailId) {
            //更新工单工序详情
            var detail = record.load({type: 'customrecord_workorder_process_detail', id: detailId, isDynamic: true});
            var reportworkquantity = detail.getValue('custrecord_reportworkquantity');
            var completedquantity = detail.getValue('custrecord_completedquantity');
            var defectiveqty = detail.getValue('custrecord_defectiveqty');
            var scrapquantity = detail.getValue('custrecord_scrapquantity');
            detail.setValue('custrecord_reportworkquantity', reportworkquantity + newRecord.getValue('custbody_reportwork_qty'));//报工数量
            detail.setValue('custrecord_completedquantity', completedquantity + newRecord.getValue('completedquantity'));//已完成数量
            detail.setValue('custrecord_defectiveqty', defectiveqty + newRecord.getValue('custbody_defectivequantity'));//次品数量
            detail.setValue('custrecord_scrapquantity', scrapquantity + newRecord.getValue('custbody_processscrapquantity'));//工序废品数量
            detail.save();
        }


    }

    function createOrUpdateNextProcessDetailRecordAndItemsCompletion(woId, startoperationText, assemblyItemId) {
        var detailNextId;
        search.create({
            type: 'customrecord_workorder_process_detail',
            columns: [],
            filters: [['custrecord_workordernum', 'is', woId],
                'and', ['custrecord_processnum', 'equalto', parseInt(startoperationText) + 1],
                'and', ['custrecord_assembly', 'is', assemblyItemId]]
        }).run().each(function (result) {
            detailNextId = result.id;
        });
        log.debug('createOrUpdateNextProcessDetailRecordAndItemsCompletion', detailNextId);
        if (!detailNextId) {//下一道工单工序详情不存在
            //创建下一道工单工序详情
            var detailNextRec = record.create({type: 'customrecord_workorder_process_detail', isDynamic: true});
            var operationTaskNextId = results[parseInt(startoperationText)].id;
            detailNextRec.setValue('custrecord_workordernum', woId);//工单号
            detailNextRec.setValue('custrecord_processnum', (parseInt(startoperationText) + 1));//工序号
            detailNextRec.setValue('custrecord_assembly', assemblyItemId);//装配件
            detailNextRec.setValue('custrecord_externalprocess', operationTaskNextId);//单位
            detailNextRec.setValue('custrecord_process_type', getProcessTypeIdByOperationTaskId(operationTaskNextId));//工序类型
            detailNextRec.setValue('custrecord_workunit', woUnits);//工单单位

            //创建下一道工单工序详情明细行
            detailNextRec.selectNewLine('recmachcustrecord_workorderprocess');
            detailNextRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_item', assemblyItemId);//设置货品
            detailNextRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', newRecord.getValue('completedquantity'));//设置耗料数量
            detailNextRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_releasequantity', newRecord.getValue('completedquantity'));//设置发料数量
            detailNextRec.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_unit', woUnits);//设置单位
            detailNextRec.commitLine('recmachcustrecord_workorderprocess');

        } else {
            var detailNext = record.load({
                type: 'customrecord_workorder_process_detail',
                id: detailNextId,
                isDynamic: true
            });
            var lineNumber = detailNext.findSublistLineWithValue('recmachcustrecord_workorderprocess', 'custrecord_item', assemblyItemId);
            if (lineNumber !== -1) {//找到了需要更新的 工单工序明细行
                var issueQty = detailNext.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', lineNumber);
                var releaseQty = detailNext.getSublistValue('recmachcustrecord_workorderprocess', 'custrecord_releasequantity', lineNumber);
                detailNext.selectLine('recmachcustrecord_workorderprocess', lineNumber);
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', issueQty + newRecord.getValue('completedquantity'));
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_releasequantity', releaseQty + newRecord.getValue('completedquantity'));//设置发料数量
                detailNext.commitLine('recmachcustrecord_workorderprocess');
            } else {//没找到则 新建一行
                //创建工单工序详情明细行
                detailNext.selectNewLine('recmachcustrecord_workorderprocess');
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_item', assemblyItemId);//设置货品
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_issuequantity', newRecord.getValue('completedquantity'));//设置耗料数量
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_releasequantity', newRecord.getValue('completedquantity'));//设置发料数量
                detailNext.setCurrentSublistValue('recmachcustrecord_workorderprocess', 'custrecord_unit', woUnits);//设置单位
                detailNext.commitLine('recmachcustrecord_workorderprocess');
            }
            detailNext.save();
        }
    }


    return {
        beforeSubmit: beforeSubmit,
        afterSubmit: afterSubmit
    };
});